package com.fly.video.downloader;

import com.fly.video.downloader.bean.Video;
import com.fly.video.downloader.content.Recv;
import com.fly.video.downloader.content.analyzer.AnalyzerTask;
import com.fly.video.downloader.content.history.History;
import com.fly.video.downloader.core.content.ClipboardManager;
import com.fly.video.downloader.layout.listener.VideoFragmentListener;
import com.fly.video.downloader.slice.MainAbilityNewSlice;
import com.fly.video.downloader.util.Helpers;
import com.fly.video.downloader.util.io.FileStorage;
import com.fly.video.downloader.util.network.DownloadQueue;
import com.fly.video.downloader.util.network.Downloader;
import com.isotne.glidelibrary.utils.OhosGlide;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.components.webengine.ResourceError;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.common.Source;
import ohos.media.photokit.metadata.AVStorage;
import ohos.media.player.Player;
import ohos.net.http.SslError;
import ohos.utils.net.Uri;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainAbilityNew extends Ability implements AnalyzerTask.AnalyzeListener, DownloadQueue.QueueListener {
    static final HiLogLabel logLabel=new HiLogLabel(HiLog.LOG_APP,0x001010,"主界面");
    public static final int CODE_HISTORY=1001;
    public static final int SEARCH_HISTORY=1002;
    private String lastClip = "";
    protected ProgressBar progressBar;
    Image avatar;
    Text nickname;
    Text content;
    Text videoState;
    private SurfaceProvider sfProvider;
    private Player player;
    private Surface surface;
    public Video video = null;
    protected DownloadQueue downloadQueue = new DownloadQueue();
    private File NowFile;
    private WebView mWebview;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        super.setMainRoute(MainAbilityNewSlice.class.getName());
        super.setUIContent(ResourceTable.Layout_ability_main_new_page);
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        String[] per = {"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_MEDIA",
                "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(per, 0);
        findComponentById(ResourceTable.Id_navigation_input_new).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName("com.fly.video.downloader")
                        .withAbilityName("com.fly.video.downloader.VideoSearchAbility")
                        .build();
                intent1.setOperation(operation);
                startAbilityForResult(intent1,SEARCH_HISTORY);
            }
        });
        findComponentById(ResourceTable.Id_navigation_history_new).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName("com.fly.video.downloader")
                        .withAbilityName("com.fly.video.downloader.HistoryAbility")
                        .build();
                intent1.setOperation(operation);
                startAbilityForResult(intent1,CODE_HISTORY);
            }
        });
        findComponentById(ResourceTable.Id_video_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                PackageManager packageManager = context.getPackageManager();
                Intent intent = new Intent();
                intent.setAction("com.ss.android.ugc.aweme");
//                Intent intent = packageManager.getLaunchIntentForPackage("com.ss.android.ugc.aweme");
                startAbility(intent,10086);
            }
        });
        downloadQueue.setQueueListener(this);
        onCreateView();
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        switch (requestCode){
            case CODE_HISTORY:
                if(resultData!=null){
                    Video video=resultData.getSerializableParam("video");
                    if(video!=null){
                        onAnalyzed(video,true);
                    }
                }
                break;
            case SEARCH_HISTORY:
                if(resultData!=null){
                    String str=resultData.getStringParam("str");
                    if(!StringUtils.isEmpty(str)){
                        Analyze(str);
                    }
                }
                break;
            default:
                break;
        }
    }

    public void onCreateView()
    {
        avatar= (Image) findComponentById(ResourceTable.Id_video_avatar);
        nickname= (Text) findComponentById(ResourceTable.Id_video_nickname);
        content= (Text) findComponentById(ResourceTable.Id_video_content);
        videoState= (Text) findComponentById(ResourceTable.Id_video_pause);
        sfProvider= (SurfaceProvider) findComponentById(ResourceTable.Id_surfaceProvider_new);
        progressBar= (ProgressBar) findComponentById(ResourceTable.Id_progress_new);
        mWebview= (WebView) findComponentById(ResourceTable.Id_webview);
        mWebview.getWebConfig().setJavaScriptPermit(true);
        mWebview.setWebAgent(new WebAgent(){
            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                super.onError(webView, request, error);
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setContentText("请尝试替换网络再试").setTitleText("提示").show();
                    }
                });
            }

            @Override
            public void onSslError(WebView webView, SslError error) {
                super.onSslError(webView, error);
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setContentText("请尝试替换网络再试").setTitleText("提示").show();
                    }
                });
            }

            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                return super.isNeedLoadUrl(webView, request);
            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                onWebviewPreseOk(url);
                //取到重定向之后的url就不需要继续加载了
                super.onPageLoaded(webView, "https://www.baidu.com/");
            }
        });
        initPlayer();
    }
    private void initPlayer() {
        sfProvider.pinToZTop(false);
        WindowManager.getInstance().getTopWindow().get().setTransparent(true);
        //sfProvider添加监听事件
        sfProvider.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(player.isNowPlaying()){
                    //如果正在播放，就暂停
                    player.pause();
                    //播放按钮可见
                    videoState.setVisibility(Component.VISIBLE);
                }else {
                    //如果暂停，点击继续播放
                    player.play();
                    //播放按钮隐藏
                    videoState.setVisibility(Component.HIDE);
                }
            }
        });
        sfProvider.getSurfaceOps().get().addCallback(new VideoSurfaceCallback());
        player=new Player(getContext());
    }

    @Override
    public void onAnalyzed(Video video) {
        onAnalyzed(video, false);
    }
    public void onAnalyzed(Video video, boolean fromHistory)
    {
            if (this.video == video)
                return;

        this.video = video;
        if (!fromHistory)
            onHistoryAppend(video);

        downloadQueue.clear();
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                nickname.setText(video.getUser().getNickname());
                content.setText(video.getTitle());
                try {
                    OhosGlide.with(getContext())
                            .load(video.getUser().getAvatarUrl())
                            .def(ResourceTable.Media_icon)
                            .into(avatar);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                //用webview转换一下url
                mWebview.load(video.getUrl());
            }
        });
    }
    private void onWebviewPreseOk(String url){
        Downloader videoDownloader = new Downloader(this,url).setFileAsDCIM(FileStorage.TYPE.VIDEO,"video-"+ video.getId() + ".mp4");
        NowFile=videoDownloader.getFile();
        if (NowFile.exists()) {
            getFileToPlayer();
        }
        else {
            downloadQueue.add("video-" + video.getId(), videoDownloader);
//                playerListener.playVideo(video.getUrl());
            try{
//                videoDownloader.start();
                downloadQueue.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onAnalyzeCanceled() {

    }

    @Override
    public void onAnalyzeError(Throwable e) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                new ToastDialog(getContext()).setContentText( e.getMessage()).setTitleText("提示").show();
            }
        });
    }

    @Override
    public void onQueueDownloaded(DownloadQueue downloadQueue, ArrayList<String> accidentHashes) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                new ToastDialog(getContext()).setContentText(getString(ResourceTable.String_download_complete)).setTitleText("提示").show();
            }
        });
        getFileToPlayer();
    }

    @Override
    public void onQueueProgress(DownloadQueue downloadQueue, long loaded, long total) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                if (total <= 0)
                    setMainProgress(0);
                else
                    setMainProgress((int)(loaded * 100 / total));
            }
        });
        if(loaded==total){
            getFileToPlayer();
        }
    }

    @Override
    public void onDownloaded(String hash, Downloader downloader) {

    }

    @Override
    public void onDownloadProgress(String hash, Downloader downloader, long loaded, long total) {

    }

    @Override
    public void onDownloadCanceled(String hash, Downloader downloader) {

    }

    @Override
    public void onDownloadError(String hash, Downloader downloader, Throwable e) {

    }

    private class VideoSurfaceCallback implements SurfaceOps.Callback {
        @Override
        public void surfaceCreated(SurfaceOps surfaceOps) {
            HiLog.info(logLabel,"surfaceCreated() called.");
            if (sfProvider.getSurfaceOps().isPresent()) {
                surface = sfProvider.getSurfaceOps().get().getSurface();
                getFileToPlayer();
            }
        }
        @Override
        public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
            HiLog.info(logLabel,"surfaceChanged() called.");
        }
        @Override
        public void surfaceDestroyed(SurfaceOps surfaceOps) {
            HiLog.info(logLabel,"surfaceDestroyed() called.");
        }
    }
    private class VideoPlayerCallback implements Player.IPlayerCallback {
        @Override
        public void onPrepared() {
            HiLog.info(logLabel, "onPrepared");
        }

        @Override
        public void onMessage(int i, int i1) {
            HiLog.info(logLabel, "onMessage");
        }

        @Override
        public void onError(int i, int i1) {
            HiLog.info(logLabel, "onError: i=" + i + ", i1=" + i1);
        }

        @Override
        public void onResolutionChanged(int i, int i1) {
            HiLog.info(logLabel, "onResolutionChanged");
        }

        @Override
        public void onPlayBackComplete() {
            //播放完成回调，重新播放
            if (player != null) {
                player.prepare();
                player.play();
            }
        }

        @Override
        public void onRewindToComplete() {
            HiLog.info(logLabel, "onRewindToComplete");
        }

        @Override
        public void onBufferingChange(int i) {
            HiLog.info(logLabel, "onBufferingChange");
        }

        @Override
        public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
            HiLog.info(logLabel, "onNewTimedMetaData");
        }

        @Override
        public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
            HiLog.info(logLabel, "onMediaTimeIncontinuity");
        }
    }
    @Override
    protected void onActive() {
        super.onActive();
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                ClipboardManager clip = new ClipboardManager(getContext());
                String str = clip.getText(0);

                if (!lastClip.equals(str))
                {
                    if (Helpers.containsDouyin(getContext(), str)) {
                        lastClip = str;
                        Intent intent1 = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                                .withBundleName("com.fly.video.downloader")
                                .withAbilityName("com.fly.video.downloader.VideoSearchAbility")
                                .build();
                        intent1.setOperation(operation);
                        intent1.setParam("lastClip",lastClip);
                        startAbilityForResult(intent1,SEARCH_HISTORY);
                        new ToastDialog(getContext()).setContentText(getString(ResourceTable.String_clip_valid)).show();
                    }
                }
            }
        });
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Recv recv = new Recv(intent);
        if (recv.isActionSend()
        ) {
            Analyze(recv.getContent());
        }
    }
    public void setMainProgress(int progress)
    {
        if (progress >= 100)
            progress = 0;
        int finalProgress = progress;
        progressBar.setProgressValue(finalProgress);
    }
    public void Analyze(String text)
    {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                new ToastDialog(getContext()).setContentText("开始分析...").show();
            }
        });
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(new AnalyzerTask(this, this,text));
    }
    public void onHistoryAppend(Video video)
    {
        History.put(video);
    }
    private void getFileToPlayer() {
        if(surface==null){
            return;
        }
        if(NowFile==null){
            return;
        }
            try {
                FileInputStream in = new FileInputStream(NowFile);
                FileDescriptor filedesc = in.getFD();
                Source source=new Source(filedesc);
                player.setSource(source);
                player.setVideoSurface(surface);
                player.setPlayerCallback(new VideoPlayerCallback());
                player.prepare();
                sfProvider.setTop(0);
                player.play();
            } catch (Exception e) {
                HiLog.info(logLabel,"playUrl Exception:" + e.getMessage());
            }
//        }
    }
}
